package cn.legend.travel.basic.info.handler;


import cn.legend.travel.common.enumerator.ServiceCode;
import cn.legend.travel.common.exception.ServiceException;
import cn.legend.travel.common.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException e){
        String message=e.getMessage();
        return JsonResult.fail(ServiceCode.ERROR_BAD_REQUEST,message);
    }
    @ExceptionHandler
    public JsonResult handleBindException(BindException e){
//        String message="";
//        List<FieldError> fieldErrorList=e.getFieldErrors();
//        for (FieldError fieldError:fieldErrorList){
//            message+=fieldError.getDefaultMessage();
//        }
        String message=e.getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERROR_BAD_REQUEST,message);
    }

    @ExceptionHandler
    public JsonResult handleServerException(ServiceException e){
        return JsonResult.fail(e);
    }

    @ExceptionHandler
    public JsonResult handleAccess(AccessDeniedException e){
        String message="您当前没有此操作权限!";
        return JsonResult.fail(ServiceCode.ERROR_FORBIDDEN,message);
    }
    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e){
        log.error("程序运行过程中出现了未处理的异常!",e);
        String message="服务器忙，请稍后再试！";
        return JsonResult.fail(ServiceCode.ERROR_UNKNOWN,message);
    }

}
